package com.xuebang.admin.web.taglib;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.displaytag.util.Href;

import com.xuebang.admin.dao.Pagination;
import com.xuebang.admin.web.displaytag.RequestHelperFactory.CustomRequestHelper;

@SuppressWarnings("serial")
public class PaginationTag extends TagSupport {

	private String name;
	private String css;
	private String uri;

	@SuppressWarnings("unchecked")
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();

		try {
			HttpServletRequest req = (HttpServletRequest) pageContext
					.getRequest();
			Pagination<Object> pagination = (Pagination<Object>) req
					.getAttribute(name);

			CustomRequestHelper requestHelper = new CustomRequestHelper(req,
					(HttpServletResponse) pageContext.getResponse());
			Href href = requestHelper.getHref();
			if (uri != null) {
				href.setFullUrl(uri);
			}

			out.append("<div class=\"").append("pagination");
			if (css != null) {
				out.append(" ").append(css);
			}
			out.append("\"><ul>");
			for (Integer p : pagination.pageNavigation()) {
				if (p == -1) {
					out.append("<li class=\"disabled\"><a href=\"#\">...</a></li>");
				} else if (p == pagination.page) {
					out.append("<li class=\"active\"><a href=\"#\">")
							.append(p.toString()).append("</a></li>");
				} else {
					href.addParameter("page", p);
					out.append("<li><a href=\"").append(href.toString())
							.append("\">").append(p.toString())
							.append("</a></li>");
				}
			}
			out.append("</ul></div>");
		} catch (IOException e) {
			throw new JspException(e);
		}

		return SKIP_BODY;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCss() {
		return css;
	}

	public void setCss(String css) {
		this.css = css;
	}

	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}

}
